package com.usian.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.common.Result;
import com.usian.common.ResultCodeEnum;
import com.usian.entity.Orders;
import com.usian.entity.Reviews;
import com.usian.entity.Users;
import com.usian.user.feign.OrderFeignClient;
import com.usian.user.mapper.ReviewsMapper;
import com.usian.user.mapper.UsersMapper;
import com.usian.user.service.IReviewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.vo.ReviewsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-15
 */
@Service
public class ReviewsServiceImpl extends ServiceImpl<ReviewsMapper, Reviews> implements IReviewsService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Override
    public Result<String> addReviews(Reviews reviews) {
        System.out.println(reviews);
        //根据userId获取carId
        Orders order = orderFeignClient.getOrderByUserId(reviews.getUserId()).getData();
        if (order == null) {
            return Result.build(null, ResultCodeEnum.ORDERS_NOT_EXISTS);
        }
        Integer carId = order.getCarId();
        reviews.setCarId(carId);
        save(reviews);
        return Result.build("yes", ResultCodeEnum.SUCCESS);
    }

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Result<List<ReviewsVo>> findReviewsAll(Integer carId) {
        LambdaQueryWrapper<Reviews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Reviews::getCarId, carId);
        wrapper.orderByDesc(Reviews::getReviewDate);
        List<Reviews> list = list(wrapper);
        if (list.isEmpty()) {
            return Result.build(null, ResultCodeEnum.REVIEWS_NOT_EXISTS);
        }
        List<ReviewsVo> reviewsVoList = new ArrayList<>();
        for (Reviews reviews : list) {
            Users user = usersMapper.selectById(reviews.getUserId());
            if (user == null) {
                return Result.build(null, ResultCodeEnum.USER_NON_EXISTS);
            }
            ReviewsVo reviewsVo = new ReviewsVo();
            BeanUtils.copyProperties(reviews, reviewsVo);
            reviewsVo.setUserName(user.getNickname());
            reviewsVo.setUserImageUrl(user.getImageUrl());
            reviewsVoList.add(reviewsVo);
        }
        return Result.build(reviewsVoList, ResultCodeEnum.SUCCESS);
    }
}
